package com.gitee.cui.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * 混合缓冲区测试类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/22 14:49
 **/
public class CompositeBufferTest {

    @Test
    public void compositeBufferTest() {
        // 混合缓冲区
        CompositeByteBuf cBuffer = ByteBufAllocator.DEFAULT.compositeBuffer();
        // 头缓冲区
        ByteBuf header = Unpooled.copiedBuffer("测试头部", StandardCharsets.UTF_8);
        // 消息体缓冲区
        ByteBuf body = Unpooled.copiedBuffer("测试消息体", StandardCharsets.UTF_8);
        // 将消息头和消息体合并到混合缓冲区，组合成理论上完整的内容
        cBuffer.addComponents(header, body);
        // 发送消息
        sendMsg(cBuffer);
        // 保留消息头，增加引用次数
        header.retain();
        cBuffer.release();

        cBuffer = ByteBufAllocator.DEFAULT.compositeBuffer();
        // 构建消息体2
        body = Unpooled.copiedBuffer("测试消息体2", StandardCharsets.UTF_8);
        cBuffer.addComponents(header, body);
        sendMsg(cBuffer);
        cBuffer.release();
    }

    /**
     * 发送消息
     * @param cBuffer 混合缓冲区
     */
    private void sendMsg(CompositeByteBuf cBuffer) {
        for (ByteBuf byteBuf : cBuffer) {
            // 可读字节数
            int length = byteBuf.readableBytes();
            byte[] array = new byte[length];
            byteBuf.getBytes(byteBuf.readerIndex(), array);
            System.out.println(new String(array, StandardCharsets.UTF_8));
        }
        System.out.println();
    }

    /**
     * 将混合缓冲区的所有缓冲区合并成一个Java NIO 缓冲区
     */
    @Test
    public void intCompositeBufCompositeTest() {
        CompositeByteBuf cBuffer = Unpooled.compositeBuffer(3);
        cBuffer.addComponent(Unpooled.wrappedBuffer(new byte[] {1, 2, 3}));
        cBuffer.addComponent(Unpooled.wrappedBuffer(new byte[] {4}));
        cBuffer.addComponent(Unpooled.wrappedBuffer(new byte[] {5, 6}));
        // 合并成一个Java NIO缓冲区
        ByteBuffer nioBuffer = cBuffer.nioBuffer(0, 6);
        byte[] array = nioBuffer.array();
        for (byte b : array) {
            System.out.print(b);
        }
        cBuffer.release();
    }
}
